import type { CardCustomAttrItem, CardInfoData } from '/@/api/general/model/cardModel';
import type { GoodWeChatUrlParams } from '/@/api/model/commonModel';
import { SearchMapValTypeEnum } from '/@/api/general/model/cardModel';
import { defineComponent, reactive, ref } from 'vue';
import ClipboardJS from 'clipboard';
import setting from '/@/settings/projectSetting';
import { useGo } from '/@/hooks/web/usePage';
import { useRouter } from 'vue-router';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGeneralGameHooks } from '/@/views/general/hooks/useConfigs';
import { aTabClick, awaitWrap } from '/@/utils';
import { appShareUsing, sharePageOpenApp } from '/@/utils/appInteractive';
import { isArray, isObject, isWeChatBrowser } from '/@/utils/is';
import { CardDetailApi } from '/@/api/general/card';
import Title from '/@/views/general/components/Title';
import { Icon } from '/@/components/Icon';
import { Skeleton, Image, Button, showImagePreview } from 'vant';
import { GoodWeChatUrlApi } from '/@/api/common';

import('./index.less');

export default defineComponent({
  name: 'GeneralCardDetailPage',
  props: {
    gameId: {
      type: String as PropType<string>,
      required: true,
    },
    id: {
      type: Number as PropType<number>,
      required: true,
    },
  },
  setup(props) {
    // 设置分享参数
    appShareUsing({
      title: '',
      content: '',
      image: '',
      url: window.location.href,
    });

    const go = useGo();

    const { getGameConfig, gameConfigData } = useGeneralGameHooks(); // gameConfigData
    getGameConfig({ game_id: props.gameId });

    const router = useRouter();
    const { createSuccessToast, createFailToast } = useMessage();

    const cardDetailInfo = reactive<CardInfoData>({} as CardInfoData);
    const loadingState = ref(true);
    const getDetail = async () => {
      const { gameId, id } = props;
      const [error, result] = await awaitWrap(CardDetailApi({ game_id: gameId, id: id }));
      if (error || !result) {
        return;
      }
      for (const item in result) {
        cardDetailInfo[item] = result[item];
      }
      loadingState.value = false;
    };
    getDetail();

    // 复制牌名
    // const { copy } = useClipboard();
    const copyName = () => {
      const clipboard = new ClipboardJS('.copy-card-name', {
        text: function () {
          const { card } = cardDetailInfo.card_fixed_attr;
          return card.name;
        },
      });
      clipboard.on('success', function () {
        createSuccessToast({
          message: '复制牌名成功',
        });
      });
      clipboard.on('error', function () {
        createFailToast({
          message: '复制牌名失败',
        });
      });
    };

    // 跳转到APP或者小程序
    const goToBuyClick = async () => {
      const { shopping, card_fixed_attr } = cardDetailInfo;
      const { card } = card_fixed_attr;
      if (isWeChatBrowser()) {
        const params: GoodWeChatUrlParams = {
          type: 'tool_card',
          good_id: {
            card_no: card.card_no,
            rarity: card.rarity!,
          },
          game_id: gameConfigData.trade_game_id,
        };
        const [error, data] = await awaitWrap(GoodWeChatUrlApi(params));
        if (error || !data) {
          aTabClick(setting.wechatAppHomeUrl, '_blank');
          return;
        }
        aTabClick(data.url_link, '_blank');
        return;
      }

      shopping.link_url ? sharePageOpenApp(shopping.link_url) : null;
    };

    const CustomCardAttrs = ({ customAttrs }: { customAttrs: CardCustomAttrItem[] }) => {
      if (!isArray(customAttrs)) {
        return null;
      }
      const AttrsArray: VueNode[] = [];
      for (const item of customAttrs) {
        if (item.style === SearchMapValTypeEnum.IMAGE) {
          const { imgs } = item;
          imgs.length
            ? AttrsArray.push(
                <li class='flex'>
                  <span>{item.title}</span>：
                  <div class={'flex flex-1 flex-wrap'}>
                    {imgs.map((src) => {
                      return <img src={src} alt='' class={'h-36px mr-sm mb-sm'} />;
                    })}
                  </div>
                </li>
              )
            : null;
        } else {
          const { text } = item;
          text
            ? AttrsArray.push(
                <li class='flex'>
                  <span>{item.title}：</span>
                  <span class={['flex-1 whitespace-pre-line']}>{text}</span>
                </li>
              )
            : null;
        }
      }
      return <>{AttrsArray}</>;
    };

    const FirstBox = () => {
      const { is_show_card_no, is_show_ename } = gameConfigData;
      const { card_fixed_attr, card_custom_attrs } = cardDetailInfo;
      const { card, series } = card_fixed_attr;
      const { up: cardUp } = card_custom_attrs;
      return (
        <div class={'first-box relative'}>
          <div class={'flex relative'}>
            <div
              class={'image'}
              onClick={() => {
                showImagePreview({
                  images: [card.img],
                  showIndex: false,
                  overlayStyle: {
                    backgroundColor: 'rgba(0,0,0,.8)',
                  },
                });
              }}
            >
              <Image src={card.img} alt='' class={'w-full'} />
            </div>
            <ul class={'info'}>
              <li>
                <Button
                  size={'mini'}
                  onClick={copyName}
                  class={'copy-card-name !rounded-full !text-blue-500'}
                  color={'#DBEDFF'}
                >
                  点击复制牌名
                </Button>
              </li>
              <li class={'text-40px font-bold my-30px leading-45px'}>
                <span>{card.name}</span>
                {is_show_ename ? <div class='text-sm font-normal text-gray-400'>{card.ename}</div> : null}
                {is_show_card_no ? <div class='text-sm font-normal text-gray-400'>{card.card_no}</div> : null}
              </li>

              {isObject(series) ? (
                <li class='flex'>
                  <span>系列：</span>
                  <span class={['flex-1 whitespace-pre-line']}>{series.name}</span>
                </li>
              ) : null}
              <CustomCardAttrs customAttrs={cardUp} />
            </ul>
          </div>
        </div>
      );
    };

    const LastBox = () => {
      const { card_fixed_attr, card_custom_attrs } = cardDetailInfo;
      const { keywords } = card_fixed_attr.card;
      const { down: downCard } = card_custom_attrs;
      return (
        <div class={'last-box'}>
          <ul>
            <CustomCardAttrs customAttrs={downCard} />
            {isArray(keywords) && keywords.length ? (
              <div class={'bg-blue-100/50 p-lg mt-md'}>
                {keywords.map((word) => {
                  return <p class={'text-[#6586B1] text-sm'}>{word}</p>;
                })}
              </div>
            ) : null}
          </ul>
        </div>
      );
    };

    const OtherVersionBox = () => {
      const { other_version } = cardDetailInfo;
      if (!other_version || !other_version.length) {
        return null;
      }
      return (
        <div class='other-box'>
          <div class={'text-gray-400 text-sm'}>其他版本</div>
          <ul class={'ver-list'}>
            {other_version.map((item) => {
              const verPrice = item.price ? item.price / 100 : 0;
              return (
                <li
                  class={'text-sm py-10px flex justify-between'}
                  onClick={() => {
                    go(`/generalcard/${props.gameId}/${item.id}`);
                  }}
                >
                  <div class={'w-[82%] van-ellipsis'}>
                    <span class={'mr-sm'}>{item.series_name}</span>
                    <span class={'mr-sm'}>{item.series_abbr}</span>
                    <span>[{item.sindex}]</span>
                  </div>
                  {verPrice ? <div class={'text-red-500'}>¥{verPrice}</div> : null}
                </li>
              );
            })}
          </ul>
        </div>
      );
    };

    const OtherLinkBox = () => {
      const { other_card_link_list, other_card_link_title } = cardDetailInfo;
      if (!other_card_link_list || !other_card_link_list.length) {
        return null;
      }
      return (
        <div class='other-box'>
          <div class={'text-gray-400 text-sm'}>{other_card_link_title}</div>
          <ul class={'ver-list'}>
            {other_card_link_list.map((item) => {
              const verPrice = item.price ? item.price / 100 : 0;
              return (
                <li
                  class={'text-sm py-10px flex justify-between'}
                  onClick={() => {
                    go(`/generalcard/${props.gameId}/${item.id}`);
                  }}
                >
                  <div class={'w-[82%] van-ellipsis'}>
                    <span class={'mr-sm'}>{item.series_name}</span>
                    <span class={'mr-sm'}>{item.series_abbr}</span>
                    <span>[{item.sindex}]</span>
                  </div>
                  {verPrice ? <div class={'text-red-500'}>¥{verPrice}</div> : null}
                </li>
              );
            })}
          </ul>
        </div>
      );
    };

    const Mall = () => {
      const { shopping } = cardDetailInfo;
      if (!isObject(shopping)) {
        return null;
      }
      return (
        <div class={'mall flex justify-center'}>
          {Number(shopping.min_price) ? (
            <ul class={'price flex items-center'}>
              <li>最低价</li>
              <li class={'nums'}>
                <span>¥</span>
                {shopping.min_price / 100}
              </li>
            </ul>
          ) : null}
          <div class={'shop-car text-base text-blue-500 flex items-center'} onClick={goToBuyClick}>
            <Icon class={'!text-lg'} icon={'material-symbols:shopping-cart-rounded'} />
            <span>前去购买</span>
          </div>
        </div>
      );
    };

    return () => (
      <div class='card-detail-container'>
        <Title
          title={cardDetailInfo.card_fixed_attr?.card?.name}
          leftArrow={true}
          onLeftClick={() => {
            router.go(-1);
          }}
        />
        <Skeleton title row={5} avatar loading={loadingState.value}>
          <div class={'detail-box'}>
            <FirstBox />
            <LastBox />
            <OtherLinkBox />
            <OtherVersionBox />
          </div>
        </Skeleton>
        <Mall />
      </div>
    );
  },
});
